// #include "Thread.h"
// #include <semaphore.h>
#include "Thread.h"
// #include "CurrentThread.h"

#include <semaphore.h>
std::atomic<int32_t> Thread::numCreated_(0);
Thread::Thread(ThreadFunc func, const std::string &name) : started_(false),
                                                           tid_(0),
                                                           func_(std::move(func)),
                                                           name_(name)
{
    setDefaultName();
}
Thread::~Thread()
{
    if (started_ && !joined_)
    {
        thread_->detach();
    }
}
void Thread::start() // 记录新线程的信息
{
    sem_t sem;
    sem_init(&sem, false, 0);
    started_ = true;
    thread_ = std::shared_ptr<std::thread>(new std::thread([&]()
                                                           {
                                                               tid_ = CurrentThread::tid(); // 获取线程的tid
                                                               sem_post(&sem);
                                                               func_(); // 执行线程函数
                                                           }));// 创建线程
    sem_wait(&sem);//保证子线程创建完成
}
void Thread::join()
{
    joined_ = true;
    thread_->join();
}
void Thread::setDefaultName()
{
    int num = ++numCreated_;
    if (name_.empty())
    {
        char buf[32] = {0};
        snprintf(buf, sizeof buf, "Thread%d", num);
        name_ = buf;
    }
};